<?php

namespace app\api\controller;

use addons\third\model\Third;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use fast\Snowflake;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;
use function fast\e;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    // 创建订单 充值会员订单
    public function create_vip_order()
    {
        $vip = Db::name("user_level")->where("id",1)->find();

        $snowflake = new Snowflake(time(), 1577836800000, 10, 12); // 10位节点ID，12位序列号，起始时间为2020-01-01 00:00:00
        $order_no = "U".$snowflake->nextId(); // 生成订单号
        $data["order_no"] = $order_no; //订单号
        $data["user_id"] = $this->auth->id; //用户id

        $data["price"] = $vip["price"]; //支付金额
        $data["vip_time"] = $vip["vip_time"]; //时长(月)
        $data["pay_status"] = 0; //支付状态 0未付款 1已支付
        $data["createtime"] = time();
        $data["level"] = $vip["id"];

        $result = Db::name("order_vip")
            ->where("user_id",$this->auth->id)
            ->where("pay_status",0)
            ->find($data);
        if (!empty($result)) {
            $result = Db::name("order_vip")->where("id",$result["id"])->update($data);

        } else {
            $result = Db::name("order_vip")->insertGetId($data);
        }

        if ($result) {
            $this->success("下单成功",$order_no);
        } else {
            $this->error("下单失败");
        }

    }



    // 创建订单
    public function create_order()
    {
        $car_old_id = input("post.car_old_id");
        if (empty($car_old_id)) {
            $this->error("参数错误");
        }

        $car_old = Db::name("car_old")->where("id", $car_old_id)->find();
        if (empty($car_old)) {
            $this->error("车源信息不存在");
        }

        if ($car_old["user_id"] == $this->auth->id) {
            $this->error("您是车源归属人，无法创建订单");
        }

        if ($car_old["status"] == 0) {
            $this->error("该车辆已下架");
        }

        if ($car_old["trade_status"] == 2) {
            $this->error("车辆正在交易中");
        }

        if ($car_old["trade_status"] == 3) {
            $this->error("车辆已售出");
        }

        //验证订单是否存在
        $this->isOrder($car_old_id);


        $result = false;
        Db::startTrans();
        try {
            $vip = Db::name("user_level")->where("id",1)->find();
            $order_auxiliary = Db::name("order_auxiliary")->insertGetId(["car_old_id" => $car_old_id]);

//            $snowflake = new Snowflake($car_old_id, 1577836800000, 10, 12); // 10位节点ID，12位序列号，起始时间为2020-01-01 00:00:00
//            $orderNumber = $snowflake->nextId(); // 生成订单号
            $order_no = "D".$order_auxiliary;
            if ($order_auxiliary > 0) {
                Db::name("car_old")->where("id", $car_old_id)->update(["trade_status"=>2]);
                $data["order_no"] = $order_no; //订单号
                $data["user_id"] = $this->auth->id; //用户id
                $data["car_old_id"] = $car_old_id; //车源id
                $data["car_old_user_id"] = $car_old["user_id"]; //车辆归属人id
                $data["car_brand_name"] = $car_old["car_brand_name"]; //品牌名称
                $data["car_series_name"] = $car_old["car_series_name"]; //车系名称
                $data["car_models_name"] = $car_old["car_models_name"]; //车型名称
                $data["car_brand_id"] = $car_old["car_brand_id"]; //品牌
                $data["car_series_id"] = $car_old["car_series_id"]; //车系
                $data["car_models_id"] = $car_old["car_models_id"]; //车型
                $data["car_image"] = $car_old["car_image"]; //车辆图片
                $data["price"] = $vip["deposit"]; //支付金额
                $data["pay_status"] = 0; //支付状态 0未付款 1已支付
                $data["refund_status"] = 0; //退款状态  默认0
                $data["status"] = 0; //订单状态 0未付款 1交易中 2交易完成
                $data["createtime"] = time();
                $data["updatetime"] = time();

                //创建订单
                $result = Db::name("order")->insertGetId($data);
                Db::name("order_auxiliary")->where("car_old_id",$car_old_id)->delete();
            }

            if ($result) {
                Db::commit();
                $this->success("下单成功",$order_no);
            } else {
                Db::rollback();
                $this->error("下单失败，请稍后再试");
            }



        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            //下单失败 重新验证订单是否存在
            $this->isOrder($car_old_id);

            $this->error("服务超时请稍后再试");
        }


    }

    function isOrder($car_old_id)
    {
        $order = Db::name("order")->field("id,status")->where("car_old_id", $car_old_id)->find();
        if (!empty($order)) {
            if ($order["status"] == 0) {
                $this->error("该车辆已被其他用户下单");
            }
            if ($order["status"] == 1) {
                $this->error("该车辆已被其他用户预定");
            }
            if ($order["status"] == 2) {
                $this->error("车辆已售出");
            }
            return false;
        }
        return true;
    }

    //我的订单
    public function my_order_list() {


        $list = Db::name("order");


        $param = input("type"); // 1 我卖出的，2 我买到的
        if (!empty($param) && $param == 2) {
            $list =  $list->where("order.user_id",$this->auth->id);
            $list =  $list->join('user u','u.id = order.car_old_user_id');

        } else {
            $list =  $list->where("car_old_user_id",$this->auth->id);
            $list =  $list->join('user u','u.id = order.user_id');
        }

        $param = input("status"); //0 待支付，1 待确认
        if ($param != "") {
            $list =  $list->where("order.status",$param)->where("refund_status",0);
        }

        $param = input("refund_status"); // 1 查询退款订单
        if (!empty($param) && $param == 1) {
            $list =  $list->where("order.refund_status",">",0);
        }



        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }

        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }

        $offset = ($page-1)*$limit;
        $list =  $list->field("order.*,c.price as car_price,c.type,c.factory_date,c.odometer_km,u.nickname,u.avatar,u.mobile");
        $list =  $list->join('car_old c','c.id = order.car_old_id');
        $list =  $list->order("order.id desc")->limit("$offset,$limit")->select();

        $this->success('请求成功',$list);
    }

    //我的订单 统计
    public function my_order_count() {





        $param = input("type"); // 1 我卖出的，2 我买到的


        $list = Db::name("order");
        if (!empty($param) && $param == 2) {
            $list =  $list->where("user_id",$this->auth->id);
        } else {
            $list =  $list->where("car_old_user_id",$this->auth->id);
        }
        $data["total"] = $list->count(); //总

        $list = Db::name("order");
        if (!empty($param) && $param == 2) {
            $list =  $list->where("user_id",$this->auth->id);
        } else {
            $list =  $list->where("car_old_user_id",$this->auth->id);
        }
        $data["value1"] = $list->where("status",1)->where("refund_status",0)->count(); //交易中

        $list = Db::name("order");
        if (!empty($param) && $param == 2) {
            $list =  $list->where("user_id",$this->auth->id);
        } else {
            $list =  $list->where("car_old_user_id",$this->auth->id);
        }
        $data["value2"] =$list->where("status",2)->where("refund_status",0)->count(); //已完成

        $list = Db::name("order");
        if (!empty($param) && $param == 2) {
            $list =  $list->where("user_id",$this->auth->id);
        } else {
            $list =  $list->where("car_old_user_id",$this->auth->id);
        }
        $data["value3"] = $list->where("refund_status",">",0)->count(); //退款

        $this->success('请求成功',$data);
    }

    //取消订单
    public function cancel_order() {
        $order_id = input("post.order_id");
        if (empty($order_id)) {
            $this->error("参数错误");
        }
        $detail = Db::name("order")->where("user_id",$this->auth->id)->where("id",$order_id)->where("status",0)->find();
        if (empty($detail)) {
            $this->error("订单已取消");
        }


        Db::startTrans();
        try {
            //修改车源状态 为在售
            $result = Db::name("car_old")->where("id",$detail["car_old_id"])->update([
                "trade_status"=>1,
            ]);
            if (!$result) {
                Db::rollback();
                $this->error("操作异常请稍后再试");
            }

            $res = Db::name("order")
                ->where("user_id",$this->auth->id)
                ->where("status",0)
                ->where("id",$order_id)
                ->update(["status"=>3]);
            if ($res) {
                Db::commit();
                $this->success('取消成功');
            } else {
                Db::rollback();
                $this->error('取消失败');
            }

        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error("服务超时请稍后再试");
        }



    }

    //删除订单
    public function del_order() {
        $order_id = input("post.order_id");
        if (empty($order_id)) {
            $this->error("参数错误");
        }
        $res = Db::name("order")
            ->where("user_id",$this->auth->id)
            ->where("status",3)
            ->where("id",$order_id)
            ->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }


    }

    //交易完成
    public function order_complete_post () {
        $id = input("order_id");
        if (empty($id)){
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $detail = Db::name("order")->where("user_id",$this->auth->id)->where("id",$id)->where("status",1)->find();
        if (empty($detail)) {
            $this->error("操作异常，请稍后再试");
        }

        Db::startTrans();
        try {

            $result = Db::name("car_old")->where("id",$detail["car_old_id"])->update([
                "trade_status"=>3,
            ]);
            if (!$result) {
                Db::rollback();
                $this->error("订单异常，请稍后再试");
            }

            $result =  Db::name("order")->where("id",$id)->update([
                "updatetime"=>time(),
                "status"=>2,
            ]);
            if (!$result) {
                Db::rollback();
                $this->error("订单异常，请稍后再试");
            }

            Db::commit();
            $this->success("交易完成");

        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error("服务超时请稍后再试");
        }
    }

    // 申请退还保障金
    public function order_refund_post()
    {
        $id = input("order_id");

        $result = Db::name("order")->where("user_id",$this->auth->id)->where("id",$id)->find();

        if ($result["refund_status"] == 1) {
            $this->success("等待审核，无需重复提交");
        }

        if ($result["refund_status"] == 3) {
            $this->success("保障金已退还，无法提交");
        }


        $data["refund_status"] = 1;
        $data["refund_reason"] = input("post.refund_reason");
        $data["refund_voucher"] = input("post.refund_voucher");
        $data["refund_apply_for_time"] = time();

        $result = Db::name("order")->where("user_id",$this->auth->id)->where("id",$id)->update($data);
        if ($result) {
            $this->success("已提交申请，等待审核");
        } else {
            $this->error("退款申请提交失败");
        }

    }

//    // 申请退款
//    public function order_refund_post()
//    {
//        $id = input("order_id");
//
//        $data["refund_status"] = 1;
//        $data["refund_reason"] = input("post.refund_reason");
//        $data["refund_voucher"] = input("post.refund_voucher");
//        $data["refund_apply_for_time"] = time();
//
//        //创建订单
//        $result = Db::name("order")->where("refund_status",0)->where("user_id",$this->auth->id)->where("id",$id)->update($data);
//        if ($result) {
//            $this->success("已提交申请，等待审核");
//        } else {
//            $this->error("退款申请提交失败");
//        }
//
//    }


}


